package com.my.study.aspect;

import com.my.study.aop.anntation.Permission;
import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.enums.RoleTypeEnum;
import com.my.study.exception.BusinessException;
import com.my.study.service.UserRoleService;
import com.my.study.vo.UserRoleVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Order(0)控制执行顺序，越小越靠前执行
 */
@Component
@Aspect
@Slf4j
@Order(0)
public class PermissionAspect {

    @Autowired
    private UserRoleService userRoleService;

    @Before("@annotation(permission)")
    public void before(JoinPoint joinPoint,Permission permission){
        // 获取请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 可从数据库获取
        List<UserRoleVO> userRoles = userRoleService.queryUserRoleInfo(request.getHeader("userId"));
        List<String> roles = userRoles.stream().map(UserRoleVO::getRoleId).collect(Collectors.toList());
        // 权限判断
        List<RoleTypeEnum> roleTypeEnums = Arrays.asList(permission.roles());
        Optional<RoleTypeEnum> optional = roleTypeEnums.stream().filter(roleTypeEnum ->
                roles.contains(roleTypeEnum.code)).findFirst();
        if(!optional.isPresent()){
            throw BusinessException.fail(BusinessExceptionEnum.FAIL.code,"当前用户没有操作权限！");
        }
    }
}
